package com.sinux.mms.common;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import com.sinux.mms.common.init.SpringInit;
import com.sinux.mms.entity.Suser;

/**
 * 超时拦截和异常处理
 * @author w.g
 * @date 2019-08-02
 * 
 */
@Component
@SuppressWarnings("all")
public class SessionTimeoutException implements HandlerInterceptor, HandlerExceptionResolver{
	public String[] allowUrls;
	
	@Override
	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler,
			Exception ex) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		System.out.println("-------------" + request.getRequestURI() + "----------------");
		try{
			Cookie[] cookes = request.getCookies();
			String sessionId = "";
			for(Cookie c:cookes){
				if(c.getName().equalsIgnoreCase("jsessionid")){
					sessionId = c.getValue().toString();
				}
			}
			//放行allowUrls中配置的url
	        for (String url:allowUrls ) {
	      
                if (request.getRequestURI().indexOf(url)>=0) {
                    return true;
                }
	            
	        }
	        //非登录请求,验证session
			if (request.getRequestURI().indexOf("/checklog") < 0) { 
				Suser user = (Suser)request.getSession().getAttribute(SpringInit.SESSION_SUSER_NAME);
				if(null != user) {
					return true;
				}else {
					if(isRequestAjax(request)){
						response.setHeader("ajaxSessionTimeOutStatus", "0");
					}else{
						response.sendRedirect(request.getContextPath()+"/views/modules/logReg.jsp");
					}
					return false;
				}
				
			}
		}catch(Exception e){
			
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		System.out.println("----SessionTimeoutException--------------postHandle------------------");
		
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html;charset=UTF-8");
		System.out.println("------SessionTimeoutException------------" + requestUrl + "------------------");
		
	}
	public String[] getAllowUrls() {
		return allowUrls;
	}

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}
	
	private boolean isRequestAjax(HttpServletRequest request){
		 String headerX = request.getHeader("X-Requested-With");           
        return headerX != null  && headerX.equalsIgnoreCase("XMLHttpRequest");     
	}

}
